<template>
  <div class="users-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 头部搜索框 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model.trim="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="openAddUserDialog"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表单区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话号码"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row.mg_state, scope.row.id)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top-start" :enterable="false">
              <el-button
                @click="openEditDialog(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
            </el-tooltip>

            <el-tooltip content="删除" placement="top-start" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <AddUserDialog @updateList="updateList"></AddUserDialog>

      <!-- 修改用户数据对话框 -->
      <EditDialog @updateList="updateList"></EditDialog>
    </el-card>
  </div>
</template>

<script>
import EditDialog from '@/components/user/EditDialog.vue'
import AddUserDialog from '@/components/user/AddUserDialog.vue'
export default {
  name: 'Users',
  data() {
    // 自定义检验规则和匹配正则
    const emailzz = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
    const numberzz =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    const checkEmail = (rule, value, cb) => {
      if (value === '') return cb(new Error('邮箱不能为空!'))
      if (emailzz.test(value)) {
        cb()
      } else {
        cb(new Error('邮箱格式不正确!'))
      }
    }
    const checkNumber = (rule, value, cb) => {
      if (value === '') return cb(new Error('手机号码不能为空!'))
      if (numberzz.test(value)) {
        cb()
      } else {
        cb(new Error('号码格式不正确!'))
      }
    }
    return {
      // 查询用户得请求参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      userSettingVisible: false,
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' },
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ]
      },
      editFormList: {}
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户失败!')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变得事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值发送变化得事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听状态开关,修改用户状态
    async changeState(state, id) {
      const { data: res } = await this.$http.put(`users/${id}/state/${state}`)
      if (res.meta.status !== 200) {
        state = !state
        return this.$message.error('修改失败!')
      }
      this.$message.success('修改成功!')
    },
    // 删除用户功能,并弹出确定对话框
    async deleteUser(id) {
      this.$confirm('此操作将永久删除此用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败!')
          this.getUserList()
          this.$router.push('/home/users')
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 向修改用户数据组件发送当前点击的用户id，并打开修改对话框
    async openEditDialog(id) {
      const {
        data: { data: res }
      } = await this.$http.get('users/' + id)
      this.$store.commit('user/editData', res)
      this.$store.commit('user/editDialog', true)
    },
    updateList() {
      this.getUserList()
    },
    openAddUserDialog() {
      this.$store.commit('user/AddDialog', true)
    }
  },
  components: { EditDialog, AddUserDialog }
}
</script>

<style lang="less" scoped></style>
